<template>
  <div class="orders-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderId" placeholder="请输入订单号" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择订单状态" clearable>
            <el-option v-for="item in orderStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 订单列表 -->
    <div class="order-list" v-loading="loading">
      <div v-if="orders.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无订单数据" />
      </div>
      <div v-for="order in orders" :key="order.id" class="order-card">
        <div class="order-header">
          <div class="order-info">
            <span class="order-id">订单号：{{ order.orderId }}</span>
            <span class="order-date">下单时间：{{ order.createTime }}</span>
          </div>
          <div class="order-status" :class="order.status">
            {{ getStatusText(order.status) }}
          </div>
        </div>

        <div class="order-items">
          <div v-for="item in order.items" :key="item.id" class="order-item">
            <el-image :src="item.image || item.productImage" class="item-image" />
            <div class="item-info">
              <div class="item-name">{{ item.name || item.productName }}</div>
              <div class="item-price">¥{{ item.price }}</div>
            </div>
            <div class="item-quantity">x{{ item.quantity }}</div>
          </div>
        </div>

        <div class="order-footer">
          <div class="order-amount">
            <span>共{{ getTotalQuantity(order.items) }}件商品</span>
            <span class="total-amount">
              实付款：
              <span class="price">¥{{ getTotalAmount(order.items) }}</span>
            </span>
          </div>
          <div class="order-actions">
            <el-button v-if="order.status === 1" type="primary" @click="handlePay(order)">
              立即付款
            </el-button>
            <el-button v-if="order.status === 3" type="success" @click="handleConfirmReceive(order)">
              确认收货
            </el-button>
            <el-button v-if="order.status === 4" type="primary" plain @click="handleReview(order)">
              评价
            </el-button>
            <el-button v-if="order.status === 1" type="danger" plain @click="handleCancel(order)">
              取消订单
            </el-button>
            <el-button v-if="order.status === 2 || order.status === 3 || order.status === 4" type="warning" plain @click="handleRefund(order)">
              申请退款
            </el-button>
            <el-button link type="primary" @click="viewOrderDetail(order)">
              订单详情
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination :current-page="currentPage" :page-size="pageSize" :total="total" :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 评价对话框 -->
    <el-dialog v-model="reviewDialogVisible" title="商品评价" width="500px">
      <el-form :model="reviewForm" label-width="80px">
        <el-form-item label="评分">
          <el-rate v-model="reviewForm.rating" />
        </el-form-item>
        <el-form-item label="评价内容">
          <el-input v-model="reviewForm.content" type="textarea" rows="4" placeholder="请输入您的评价内容" maxlength="500"
            show-word-limit />
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload action="/api/upload" list-type="picture-card" :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReview">提交评价</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图片预览 -->
    <el-dialog v-model="previewVisible">
      <img w-full :src="previewImage" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'

const router = useRouter()

// 搜索表单
const searchForm = reactive({
  orderId: '',
  status: '',
  dateRange: []
})

// 订单状态选项
const orderStatusOptions = [
  { value: 0, label: '已取消' },
  { value: 1, label: '待付款' },
  { value: 2, label: '待发货' },
  { value: 3, label: '待收货' },
  { value: 4, label: '已完成' },
  { value: 5, label: '退款中' },
  { value: 6, label: '已退款' }
]

// 订单数据
const orders = ref([])
const loading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 评价相关
const reviewDialogVisible = ref(false)
const reviewForm = reactive({
  rating: 5,
  content: ''
})
const previewVisible = ref(false)
const previewImage = ref('')

// 获取订单状态文本
const getStatusText = (status) => {
  const option = orderStatusOptions.find(item => item.value === status)
  return option ? option.label : ''
}

// 状态值转换（数据库状态值转前端状态值）
const getStatusKey = (statusValue) => {
  const statusMap = {
    0: 'pending',    // 待付款
    1: 'paid',       // 已付款
    2: 'shipped',    // 已发货
    3: 'completed',  // 已完成
    4: 'cancelled'   // 已取消
  }
  return statusMap[statusValue] || 'pending'
}

// 前端状态值转数据库状态值
const getStatusValue = (statusKey) => {
  const statusMap = {
    'pending': 0,    // 待付款
    'paid': 1,       // 已付款
    'shipped': 2,    // 已发货
    'completed': 3,  // 已完成
    'cancelled': 4   // 已取消
  }
  return statusMap[statusKey]
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 计算商品总数量
const getTotalQuantity = (items) => {
  return items.reduce((total, item) => total + item.quantity, 0)
}

// 计算订单总金额
const getTotalAmount = (items) => {
  return items.reduce((total, item) => total + item.price * item.quantity, 0).toFixed(2)
}

// 获取订单列表
const fetchOrders = async () => {
  loading.value = true
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.id) {
      ElMessage.warning('请先登录')
      return
    }

    const params = {
      page: currentPage.value,
      size: pageSize.value,
      userId: userInfo.id
    }

    // 添加搜索条件
    if (searchForm.orderId) {
      params.orderNo = searchForm.orderId
    }
    if (searchForm.status) {
      params.status = getStatusValue(searchForm.status)
    }

    const res = await request.get('/orders/page', { params })
    if (res.code === 200) {
      orders.value = res.data.content || []
      total.value = res.data.totalElements || 0

      console.log('原始订单数据:', res.data.content)

      // 转换订单数据格式
      orders.value = orders.value.map(order => {
        console.log('处理订单:', order.orderNo, '订单项:', order.orderItems)
        return {
          ...order,
          orderId: order.orderNo,
          createTime: formatDateTime(order.createTime),
          status: order.status, // 直接使用数字状态码
          items: (order.orderItems || []).map(item => ({
            ...item,
            image: item.productImage,
            name: item.productName,
            price: item.price || 0,
            quantity: item.quantity || 1
          }))
        }
      })

      console.log('转换后的订单数据:', orders.value)
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchOrders()
}

// 重置搜索
const resetSearch = () => {
  searchForm.orderId = ''
  searchForm.status = ''
  searchForm.dateRange = []
  currentPage.value = 1
  fetchOrders()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchOrders()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchOrders()
}

// 立即付款
const handlePay = (order) => {
  router.push({
    path: '/home/checkout',
    query: { orderId: order.id }
  })
}

// 确认收货
const handleConfirmReceive = async (order) => {
  try {
    await ElMessageBox.confirm('确认已收到商品？', '确认收货', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await request.put(`/orders/${order.id}/confirm-receive`)
    if (res.code === 200) {
      ElMessage.success('确认收货成功')
      fetchOrders() // 刷新订单列表
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error)
      ElMessage.error('确认收货失败')
    }
  }
}

// 评价
const handleReview = (order) => {
  reviewDialogVisible.value = true
}

// 取消订单
const handleCancel = async (order) => {
  try {
    await ElMessageBox.confirm('确定要取消该订单吗？', '取消订单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await request.put(`/orders/${order.id}/cancel`)
    if (res.code === 200) {
      ElMessage.success('订单取消成功')
      fetchOrders() // 刷新订单列表
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

// 申请退款
const handleRefund = async (order) => {
  try {
    await ElMessageBox.confirm('确定要申请退款吗？退款将在3-5个工作日内到账。', '申请退款', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await request.post(`/orders/${order.id}/refund`)
    if (res.code === 200) {
      ElMessage.success('退款申请已提交，请耐心等待处理')
      fetchOrders() // 刷新订单列表
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('申请退款失败:', error)
      ElMessage.error('申请退款失败')
    }
  }
}

// 查看订单详情
const viewOrderDetail = (order) => {
  router.push({
    name: 'OrderDetail',
    params: { id: order.id }
  })
}

// 提交评价
const submitReview = () => {
  // 这里应该调用API提交评价
  ElMessage.success('评价提交成功')
  reviewDialogVisible.value = false
}

// 图片上传相关
const handleRemove = (file, fileList) => {
  console.log(file, fileList)
}

const handlePictureCardPreview = (file) => {
  previewImage.value = file.url
  previewVisible.value = true
}



// 页面初始化
onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.orders-container {
  padding: 20px;
}

.search-bar {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.order-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #EBEEF5;
}

.order-info {
  display: flex;
  gap: 20px;
  color: #606266;
}

.order-id {
  font-weight: bold;
}

.order-status {
  font-weight: bold;
}

.order-status.pending {
  color: #E6A23C;
}

.order-status.paid {
  color: #409EFF;
}

.order-status.shipped {
  color: #67C23A;
}

.order-status.completed {
  color: #909399;
}

.order-status.cancelled {
  color: #F56C6C;
}

.order-items {
  padding: 15px 0;
}

.order-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.item-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  margin-right: 15px;
}

.item-info {
  flex: 1;
}

.item-name {
  margin-bottom: 5px;
}

.item-price {
  color: #F56C6C;
  font-weight: bold;
}

.item-quantity {
  color: #909399;
  margin-left: 20px;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px solid #EBEEF5;
}

.order-amount {
  display: flex;
  align-items: center;
  gap: 20px;
}

.total-amount {
  font-size: 14px;
}

.total-amount .price {
  color: #F56C6C;
  font-size: 18px;
  font-weight: bold;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 夜间模式样式 */
html.dark .orders-container {
  color: var(--el-text-color-primary);
}

html.dark .search-bar {
  background: #2a2a2a !important;
  border: 1px solid #404040;
  color: var(--el-text-color-primary);
}

html.dark .order-card {
  background: #2a2a2a !important;
  border: 1px solid #404040;
  color: var(--el-text-color-primary);
}

html.dark .order-header {
  border-bottom-color: #404040;
}

html.dark .order-info {
  color: var(--el-text-color-secondary);
}

html.dark .order-id {
  color: var(--el-text-color-primary);
}

html.dark .order-footer {
  border-top-color: #404040;
}

html.dark .item-name {
  color: var(--el-text-color-primary);
}

html.dark .item-quantity {
  color: var(--el-text-color-secondary);
}

html.dark .order-amount {
  color: var(--el-text-color-primary);
}

html.dark .total-amount {
  color: var(--el-text-color-primary);
}
</style>